#version 330 core

#define MAX 16

in vec2 UV;
in vec3 Position_worldspace;
in vec3 EyeDirection_cameraspace;
in vec3 LightDirection_cameraspace[MAX];

in vec3 o_vertexNormal_modelspace;
in vec3 o_vertexTangent_modelspace;
in vec3 o_vertexBitangent_modelspace;

out vec3 color;

uniform vec3 AmbientColor;
uniform vec3 DifuseColor;
uniform vec3 SpecularColor;
uniform float Shines;

//uniform sampler2D SpecularTextureSampler;
uniform sampler2D DiffuseTextureSampler; //texture
uniform sampler2D AmbientTextureSampler;
uniform sampler2D NormalTextureSampler;

uniform mat3 MV3x3;

uniform int NoLights;

uniform vec3 LightPosition[MAX];
uniform vec3 LightColor[MAX];
uniform float LightPower[MAX];

void main(){
	vec3 MaterialDiffuseColor = DifuseColor * texture2D( DiffuseTextureSampler, UV ).rgb;
	vec3 MaterialAmbiantColor = AmbientColor * texture2D( AmbientTextureSampler, UV ).rgb;
	vec3 MaterialSpecularColor = SpecularColor; 

	vec3 TextureNormal_tangentspace = normalize(texture2D( NormalTextureSampler, UV ).rgb*2.0 - 1.0);
	
	mat3 TBN = transpose(mat3(
		MV3x3 * o_vertexTangent_modelspace,
		MV3x3 * o_vertexBitangent_modelspace,
		MV3x3 * o_vertexNormal_modelspace	
	)); // You can use dot products instead of building this matrix and transposing it. See References for details.

	vec3 EyeDirection_tangentspace =  TBN * normalize(EyeDirection_cameraspace);
	vec3 n = TextureNormal_tangentspace;
	vec3 E = normalize(EyeDirection_tangentspace);
	
	//color = MaterialAmbiantColor;
	color = vec3(0);
	for(int i = 0; i < MAX; i++)
	{
		vec3 LightDirection_tangentspace = TBN * normalize(LightDirection_cameraspace[i]);
		float distance = length( LightPosition[i] - Position_worldspace );
		
		vec3 l = LightDirection_tangentspace;
		float cosTheta = clamp( dot( n,l ), 0,1 );
		vec3 R = reflect(-l,n);
		
		float cosAlpha = clamp( dot( E,R ), 0,1 );
		
		color += 
		// Diffuse : "color" of the object
		MaterialDiffuseColor * LightColor[i] * LightPower[i] * cosTheta / (distance*distance) +
		// Specular : reflective highlight, like a mirror
		MaterialSpecularColor * LightColor[i] * LightPower[i] * pow(cosAlpha,5) / (distance*distance);

		//color.xyz = LightDirection_tangentspace;
		
	}
}